package com.jushu.storbox;

//import java.io.File;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.jushu.storbox.adapter.FileBrowserPictureAdapter;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.entities.ImageBean;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
//import com.huawei.svn.sdk.fsm.SvnFile;

/**
 * 
 */
public class FileBrowserPictureActivity extends Activity implements OnClickListener{

	private final static String LOG_TAG = "FileBrowserPictureActivity";

	private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();

	private List<ImageBean> list = new ArrayList<ImageBean>();

	private final static int HANDLER_CODE_SCAN_COMPLETED = 1;

	protected static final int HANDLE_SHOW_PICTURE = 2;

	private ProgressDialog mProgressDialog;

	private FileBrowserPictureAdapter adapter;

	private GridView mGroupGridView;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HANDLER_CODE_SCAN_COMPLETED:
				mProgressDialog.dismiss();
				new SetAdapterAsyncTask().execute();
				break;
				
			case HANDLE_SHOW_PICTURE:
				ArrayList<String> list = (ArrayList<String>) msg.obj;
				showPicture(list);
				break;
			}
		}

		private void showPicture(ArrayList<String> list) {
			try {
				Intent intent = new Intent(FileBrowserPictureActivity.this,
						LookImageActivity.class);
				intent.putStringArrayListExtra("allImageUrl", list);
				intent.putExtra("position", 0);
				startActivityForResult(intent, 2);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private View mBtnBack;

	class SetAdapterAsyncTask extends AsyncTask<Object, Void, Integer> {
		@Override
		protected Integer doInBackground(Object... arg0) {
			list = subGroupOfImage(mGruopMap);
			if (list != null) {
				return 0;
			} else {
				return 1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result == 0) {
				List<ImageBean> a = new ArrayList<ImageBean>();
				a.add(new ImageBean());
				a.addAll(list);
				list = a;

				adapter = new FileBrowserPictureAdapter(
						FileBrowserPictureActivity.this, list, mGroupGridView);
				mGroupGridView.setAdapter(adapter);
			} else if (result == 1) {
				Toast.makeText(
						FileBrowserPictureActivity.this,
						FileBrowserPictureActivity.this.getResources()
								.getString(R.string.allfile_not_found_pic),
						Toast.LENGTH_LONG).show();
				
				List<ImageBean> a = new ArrayList<ImageBean>();
				a.add(new ImageBean());
//				a.addAll(list);
//				list = a;

				adapter = new FileBrowserPictureAdapter(
						FileBrowserPictureActivity.this, a, mGroupGridView);
				mGroupGridView.setAdapter(adapter);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.i(LOG_TAG, "onCreate()");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_picture);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG,
				FileBrowserPictureActivity.this);
		findViews();
		scanImages();
		setLiteners();
	}

	private void findViews() {
		mGroupGridView = (GridView) findViewById(R.id.all_pic);
		mBtnBack = findViewById(R.id.layout_back);
	}

	private void setLiteners() {
		mGroupGridView.setOnItemClickListener(new OnItemClickListenerImpl());
		mBtnBack.setOnClickListener(this);
	}

	private void scanImages() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		mProgressDialog = ProgressDialog.show(
				this,
				null,
				FileBrowserPictureActivity.this.getResources().getString(
						R.string.loading)
						+ "...");

		new Thread(new Runnable() {

			@Override
			public void run() {
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = FileBrowserPictureActivity.this
						.getContentResolver();

				String selection = null;
				String[] selectionArgs = getResources().getStringArray(
						R.array.SUFFIX_PIC_MIME);

				if (null != selectionArgs && selectionArgs.length > 0) {
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < selectionArgs.length; i++) {
						sb.append(MediaStore.Images.Media.MIME_TYPE + "=? or ");
					}
					int len = sb.length();
					sb.delete(len - 4, len - 1);
					selection = sb.toString();
				}

				Cursor mCursor = mContentResolver.query(mImageUri, null,
						selection, selectionArgs,
						MediaStore.Images.Media.DATE_MODIFIED);

				while (mCursor.moveToNext()) {
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
					File file = new File(path);
					if (!file.exists() || 0 >= file.length()) {
						continue;
					}
					String parentName = new File(path).getParentFile()
							.getName();

					if (!mGruopMap.containsKey(parentName)) {
						List<String> chileList = new ArrayList<String>();
						chileList.add(path);
						mGruopMap.put(parentName, chileList);
					} else {
						mGruopMap.get(parentName).add(path);
					}
				}
				mCursor.close();
				mHandler.sendEmptyMessage(HANDLER_CODE_SCAN_COMPLETED);
			}
		}).start();

	}

	/**
	 * @param mGruopMap
	 * @return
	 */
	private List<ImageBean> subGroupOfImage(
			HashMap<String, List<String>> mGruopMap) {
		if (mGruopMap.size() == 0) {
			return null;
		}
		List<ImageBean> list = new ArrayList<ImageBean>();

		Iterator<Map.Entry<String, List<String>>> it = mGruopMap.entrySet()
				.iterator();
		while (it.hasNext()) {
			Map.Entry<String, List<String>> entry = it.next();
			ImageBean mImageBean = new ImageBean();
			String key = entry.getKey();
			List<String> value = entry.getValue();

			mImageBean.setFolderName(key);
			mImageBean.setImageCounts(value.size());
			mImageBean.setTopImagePath(value.get(0));

			list.add(mImageBean);
		}
		return list;
	}

	private class OnItemClickListenerImpl implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (position == 0) {
				PublicTools.capturePicture(FileBrowserPictureActivity.this);
				return;
			}

			List<String> childList = mGruopMap.get(list.get(position)
					.getFolderName());

			Intent mIntent = new Intent(FileBrowserPictureActivity.this,
					ShowImageActivity.class);
			mIntent.putStringArrayListExtra("data",
					(ArrayList<String>) childList);
			mIntent.putExtra("parentDir", list.get(position).getFolderName());
			startActivityForResult(mIntent, 2);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case MessageCode.UPLOAD_SELECT_FILE_RESULTCODE:
			setResult(MessageCode.UPLOAD_SELECT_FILE_RESULTCODE, data);
			FileBrowserPictureActivity.this.finish();
			break;
		default:
			break;
		}

		if (resultCode != RESULT_OK) {
			return;
		}
		// if(data == null)return;
		switch (requestCode) {
		case Constant.REQUEST_CODE_TAKE_PICTURE:
			ArrayList<String> list = new ArrayList<String>();
			list.add(ClientConfig.ONEBOX_TAKE_PHOHO_DIC + File.separator + ClientConfig.PICTURE_NAME);
			Message msg = new Message();
			msg.what = HANDLE_SHOW_PICTURE;
			msg.obj = list;
			mHandler.sendMessageDelayed(msg, 500);
			break;
		case Constant.REQUEST_PHOTO_RESULT:
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LogUtil.i(LOG_TAG, "onCreate()");
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_back:
			onBackPressed();
			break;

		default:
			break;
		}
		
	}
}
